package com.aisoback.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aisoback.model.Posts;
import com.aisoback.service.PostsService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * CommandLineRunner该类实现 CommandLineRunner 接口，
 * 表示应用启动后会运行特定方法。具体功能需查看实际执行的方法。通常用于应用程序启动时执行初始化任务。
 * 此类定义尚未给出具体功能实现，请提供类中的方法以便进一步解释。
 */
//注释掉@Component，就能取消SpringBoot项目启动时自动执行该类中的方法。
//@Component
@Slf4j
public class GetPosts implements CommandLineRunner {

    @Resource
    private PostsService postsService;

    public void run(String... args) throws Exception {
        List postList = new ArrayList();
        //1.获取数据
        String json = "{\n" +
                "  \"pageSize\": 10,\n" +
                "  \"sortOrder\": \"descend\",\n" +
                "  \"sortField\": \"createTime\",\n" +
                "  \"tags\": [],\n" +
                "  \"current\": 1,\n" +
                "  \"reviewStatus\": 1\n" +
                "}";
        String url = "https://api.code-nav.cn/api/essay/list/page/vo";
        String result = HttpRequest
                .post(url)
                .body(json)
                .execute()
                .body();
        //2.json转对象
        Map<String, Object> map = JSONUtil.toBean(result, Map.class);
        JSONObject data = (JSONObject) map.get("data");
        JSONArray records = (JSONArray) data.get("records");
        for (Object record : records) {
            // 3.对象转实体
            JSONObject recordJson = (JSONObject) record;
            Posts posts = new Posts();
            if (recordJson.getStr("title") != null) {
                posts.setTitle(recordJson.getStr("title"));
            } else {
                posts.setTitle("标题失踪了");
            }
            posts.setContent(recordJson.getStr("content"));
            posts.setAuthorId(1);
            postList.add(posts);
        }
        for (Object post : postList) {
            System.out.println("数据" + post);
        }
        boolean b = postsService.saveBatch(postList);
        log.info("批量插入成功：" + b);
        log.info("获取条数为：" + postList.size());
    }
}





